package com.adaxi.adc.business.vehicletrip.listener;

import com.adaxi.adc.business.vehicletrip.service.VehicleTripService;
import com.adaxi.adc.business.vehicletrip.websocket.WebSocketServer;
import com.adaxi.adc.common.dto.CarpoolRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * @author 涛哥
 * @version 1.0
 */

@Component
@RocketMQMessageListener(topic = "pooling-topic", consumerGroup = "group1")
public class CaroolingConsumer implements RocketMQListener<CarpoolRequest> {

    final WebSocketServer webSocketServer;
    final ObjectMapper objectMapper;
    final VehicleTripService vehicleTripService;

    public CaroolingConsumer(WebSocketServer webSocketServer, ObjectMapper objectMapper, VehicleTripService vehicleTripService) {
        this.webSocketServer = webSocketServer;
        this.objectMapper = objectMapper;
        this.vehicleTripService = vehicleTripService;
    }

    @Override
    public void onMessage(CarpoolRequest carpoolRequest) {
        try {
            String message = objectMapper.writeValueAsString(carpoolRequest);
            if (webSocketServer != null) {
                String tripId = carpoolRequest.getTripId();
                Long vehicleId = vehicleTripService.getVehicleIdByTripId(tripId); // 获取车辆id

                webSocketServer.sendOneMessage(vehicleId.toString(), message);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            System.err.println("将 CarpoolRequest 转换为 JSON 时出错。");
        }
    }
}
